//package com.wechat;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.xiaomi.appstore.constant.WeChatUrlConstants;
//import com.xiaomi.appstore.crm.model.CrmAppInfo;
//import com.xiaomi.appstore.crm.model.CrmWechatExternalContact;
//import com.xiaomi.appstore.crm.model.CrmWechatGroup;
//import com.xiaomi.appstore.crm.model.CrmWechatGroupLinkStaff;
//import com.xiaomi.appstore.crm.model.CrmWechatStaff;
//import com.xiaomi.appstore.crm.model.CrmWechatStaffLinkExternalUser;
//import com.xiaomi.appstore.dao.master.wechat.CrmWechatExternalContactDAO;
//import com.xiaomi.appstore.dao.master.wechat.CrmWechatGroupDAO;
//import com.xiaomi.appstore.dao.master.wechat.CrmWechatGroupLinkStaffDAO;
//import com.xiaomi.appstore.dao.master.wechat.CrmWechatStaffDAO;
//import com.xiaomi.appstore.dao.master.wechat.CrmWechatStaffLinkExternalUserDAO;
//import com.xiaomi.appstore.dao.slave.app.CrmAppInfoSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmAccountSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmWechatGroupSlaveDAO;
//import com.xiaomi.appstore.dao.slave.wechat.CrmWechatStaffLinkExternalUserSlaveDAO;
//import com.xiaomi.appstore.model.wechat.AdminAccount;
//import com.xiaomi.appstore.model.wechat.ChatDetail;
//import com.xiaomi.appstore.model.wechat.ChatListQueryRequest;
//import com.xiaomi.appstore.model.wechat.ChatListResponse;
//import com.xiaomi.appstore.model.wechat.ExternalContact;
//import com.xiaomi.appstore.model.wechat.FollowInfo;
//import com.xiaomi.appstore.util.RestUtils;
//import com.xiaomi.appstore.util.TokenUtils;
//import com.xiaomi.appstore.util.UTF8MB4;
//import com.xiaomi.appstore.util.WeChatUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.io.ClassPathResource;
//import org.springframework.core.io.Resource;
//import org.springframework.stereotype.Service;
//import org.springframework.util.CollectionUtils;
//
//import java.io.IOException;
//import java.util.*;
//import java.util.stream.Collectors;
//
//@Service
//public class CrmWechatAsyncBiz {
//    private static final Logger LOGGER = LoggerFactory.getLogger(CrmWechatAsyncBiz.class);
//
//    @Autowired
//    private WeChatUtils weChatUtils;
//    @Autowired
//    private TokenUtils tokenUtils;
//    @Autowired
//    private CrmWechatStaffDAO crmWechatStaffDAO;
//    @Autowired
//    private CrmWechatExternalContactDAO crmWechatExternalContactDAO;
//    @Autowired
//    private CrmWechatStaffLinkExternalUserDAO crmWechatStaffLinkExternalUserDAO;
//    @Autowired
//    private CrmWechatStaffLinkExternalUserSlaveDAO crmWechatStaffLinkExternalUserSlaveDAO;
//    @Autowired
//    private CrmAppInfoSlaveDAO crmAppInfoSlaveDAO;
//    @Autowired
//    private CrmWechatGroupDAO crmWechatGroupDAO;
//    @Autowired
//    private CrmWechatGroupSlaveDAO crmWechatGroupSlaveDAO;
//    @Autowired
//    private CrmWechatGroupLinkStaffDAO crmWechatGroupLinkStaffDAO;
//    @Autowired
//    private CrmAccountSlaveDAO crmAccountSlaveDAO;
//
//    private static final int departmentId;
//
//    static {
//        Resource res = new ClassPathResource("biz_config.properties");
//        Properties pros = new Properties();
//        try {
//            pros.load(res.getInputStream());
//        } catch (IOException e) {
//            LOGGER.error("init department id error", e);
//        }
//        departmentId = Integer.parseInt(pros.getProperty("department_id"));
//        LOGGER.info("init department id{}", departmentId);
//    }
//
//    /**
//     * 增量同步人员
//     */
//    public void incrementalAsync() {
//        LOGGER.info("Start WeChat incremental synchronization of personnel data");
//        String accessToken = tokenUtils.getAccessToken();
//        List<CrmWechatStaff> staffList = weChatUtils.getStaffByDepartment(accessToken, departmentId);
//        List<String> staffIdList = staffList.stream().map(CrmWechatStaff::getUserid).collect(Collectors.toList());
//        List<AdminAccount> adminAccountInfoList = crmAccountSlaveDAO.selectList(staffIdList);
//        Map<String, String> emailMap = adminAccountInfoList.stream().filter(e -> StringUtils.isNotEmpty(e.getEmail())).collect(Collectors.toMap(AdminAccount::getWeComId, AdminAccount::getEmail, (k1, k2) -> k1));
//        staffList.forEach(e -> {
//            String userid = e.getUserid();
//            String email = emailMap.get(userid);
//            e.setEmail(email);
//        });
//        crmWechatStaffDAO.replaceStaff(staffList);
//        crmWechatGroupLinkStaffDAO.deleteAll();
//        for (CrmWechatStaff crmWechatStaff : staffList) {
//            batchSaveExtContactDetail(crmWechatStaff.getUserid(), accessToken, "");
//            batchSaveGroupDetail(crmWechatStaff.getUserid(), accessToken, "");
//        }
//    }
//
//    /**
//     * 保存客户相关信息
//     */
//    void batchSaveExtContactDetail(String userId, String accessToken, String cursor) {
//        String url = String.format(WeChatUrlConstants.BATCH_EXT_CONTACT_DETAIL_URL, accessToken);
//        JSONObject jsonObject = new JSONObject();
//        List<String> strings = Collections.singletonList(userId);
//        jsonObject.put("userid_list", strings);
//        jsonObject.put("limit", 100);
//        if (StringUtils.isNotEmpty(cursor)) {
//            jsonObject.put("cursor", cursor);
//        }
//        JSONObject response = RestUtils.post(url, jsonObject, JSONObject.class);
//        JSONArray contactList = response.getJSONArray("external_contact_list");
//        for (Object contact : contactList) {
//            HashMap<String, HashMap<String, Object>> map = (HashMap) contact;
//            HashMap<String, Object> followInfoMap = map.get("follow_info");
//            FollowInfo followInfo = JSON.parseObject(JSON.toJSONString(followInfoMap), FollowInfo.class);
//            String remark = followInfo.getRemark();
//            HashMap<String, Object> externalContactMap = map.get("external_contact");
//            ExternalContact externalContact = JSON.parseObject(JSON.toJSONString(externalContactMap), ExternalContact.class);
//            //客户表
//            CrmWechatExternalContact crmWechatExternalContact = getExternalContact(externalContact, remark);
//            //客户员工关系表 只有备注了才录入
//            if (StringUtils.isNotEmpty(followInfo.getDescription())) {
//                CrmWechatStaffLinkExternalUser crmWechatStaffLinkExternalUser = new CrmWechatStaffLinkExternalUser();
//                crmWechatStaffLinkExternalUser.setExternalUserid(externalContact.getExternal_userid());
//                crmWechatStaffLinkExternalUser.setUserid(followInfo.getUserid());
//                crmWechatStaffLinkExternalUser.setAppPackageName(followInfo.getDescription());
//                CrmAppInfo crmAppInfo = crmAppInfoSlaveDAO.queryByAppPackageName(followInfo.getDescription());
//                if (Objects.nonNull(crmAppInfo)) {
//                    crmWechatStaffLinkExternalUser.setAppName(crmAppInfo.getAppName());
//                }
//                crmWechatStaffLinkExternalUser.setAddFriendTime(followInfo.getCreatetime() * 1000);
//                try {
//                    CrmWechatStaffLinkExternalUser oldLink = crmWechatStaffLinkExternalUserSlaveDAO.selectOne(crmWechatStaffLinkExternalUser.getUserid(), crmWechatStaffLinkExternalUser.getExternalUserid());
//                    if (Objects.nonNull(oldLink)) {
//                        crmWechatStaffLinkExternalUser.setId(oldLink.getId());
//                        crmWechatStaffLinkExternalUserDAO.update(crmWechatStaffLinkExternalUser);
//                    } else {
//                        crmWechatStaffLinkExternalUserDAO.add(crmWechatStaffLinkExternalUser);
//                    }
//                } catch (Exception e) {
//                    LOGGER.error("保存企微客服客户中间表失败,userid:{}==error:{}", userId, e);
//                }
//
//            }
//            try {
//                crmWechatExternalContactDAO.replaceExternalContact(crmWechatExternalContact);
//            } catch (Exception e) {
//                LOGGER.error("保存客户联系人失败,userid:{}==crmWechatExternalContact:{}==error:{}", userId, JSON.toJSONString(crmWechatExternalContact), e);
//            }
//        }
//        String nextCursor = (String) response.get("next_cursor");
//        if (StringUtils.isNotEmpty(nextCursor)) {
//            batchSaveExtContactDetail(userId, accessToken, nextCursor);
//        }
//    }
//
//    /**
//     * 保存群组相关信息
//     */
//    private void batchSaveGroupDetail(String userId, String accessToken, String cursor) {
//        String url = String.format(WeChatUrlConstants.EXT_CONTACT_GROUP_CHAT_LIST_URL, accessToken);
//        ChatListQueryRequest chatListQueryRequest = ChatListQueryRequest.builder()
//                .limit(100)
//                .cursor(cursor)
//                .owner_filter(ChatListQueryRequest.OwnerFilterDTO.builder().userid_list(Collections.singletonList(userId)).build()).build();
//
//        ChatListResponse chatListResponse = RestUtils.post(url, chatListQueryRequest, ChatListResponse.class);
//        List<ChatListResponse.GroupChatListDTO> groupChatList = chatListResponse.getGroup_chat_list();
//        if (!CollectionUtils.isEmpty(groupChatList)) {
//            List<String> chatIdList = groupChatList.stream().map(ChatListResponse.GroupChatListDTO::getChat_id).collect(Collectors.toList());
//            chatIdList.forEach(e -> {
//                CrmWechatGroup crmWechatGroup = new CrmWechatGroup();
//                String detailUrl = String.format(WeChatUrlConstants.GROUP_CHAT_URL, accessToken);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("chat_id", e);
//                jsonObject.put("need_name", 1);
//                ChatDetail chatDetail = RestUtils.post(detailUrl, jsonObject, ChatDetail.class);
//                ChatDetail.GroupChatDTO groupChat = chatDetail.getGroup_chat();
//                crmWechatGroup.setChatId(groupChat.getChat_id());
//                crmWechatGroup.setName(groupChat.getName());
//                crmWechatGroup.setOwner(groupChat.getOwner());
//                crmWechatGroup.setNotice(groupChat.getNotice());
//                crmWechatGroup.setCreateTime(groupChat.getCreate_time());
//                try {
//                    CrmWechatGroup oldCrmWechatGroup = crmWechatGroupSlaveDAO.selectOne(crmWechatGroup.getChatId());
//                    if (Objects.nonNull(oldCrmWechatGroup)) {
//                        crmWechatGroup.setId(oldCrmWechatGroup.getId());
//                        crmWechatGroupDAO.update(crmWechatGroup);
//                    } else {
//                        crmWechatGroupDAO.insert(crmWechatGroup);
//                    }
//                } catch (Exception error) {
//                    LOGGER.error("保存群组信息失败，crmWechatGroup:{}==error{}", JSON.toJSONString(crmWechatGroup), error);
//                }
//
//                List<ChatDetail.GroupChatDTO.MemberListDTO> memberList = groupChat.getMember_list();
//                List<CrmWechatGroupLinkStaff> crmWechatGroupLinkStaffList = memberList.stream().map(k -> {
//                    CrmWechatGroupLinkStaff crmWechatGroupLinkStaff = new CrmWechatGroupLinkStaff();
//                    crmWechatGroupLinkStaff.setChatId(crmWechatGroup.getChatId());
//                    crmWechatGroupLinkStaff.setUserid(k.getUserid());
//                    crmWechatGroupLinkStaff.setType(k.getType());
//                    crmWechatGroupLinkStaff.setJoinTime(k.getJoin_time());
//                    crmWechatGroupLinkStaff.setName(getNoEmojiName(k.getName()));
//                    return crmWechatGroupLinkStaff;
//                }).collect(Collectors.toList());
//
//                try {
//                    crmWechatGroupLinkStaffDAO.insertList(crmWechatGroupLinkStaffList);
//                } catch (Exception error) {
//                    LOGGER.error("保存群组客户关系失败, chatId:{}, error:{}", crmWechatGroup.getChatId(), error);
//                }
//            });
//        }
//        String nextCursor = chatListResponse.getNext_cursor();
//        if (StringUtils.isNotEmpty(nextCursor)) {
//            batchSaveExtContactDetail(userId, accessToken, nextCursor);
//        }
//    }
//
//    // 组装企微外部联系人
//    CrmWechatExternalContact getExternalContact(ExternalContact externalContact, String remark) {
//        CrmWechatExternalContact crmWechatExternalContact = new CrmWechatExternalContact();
//        if (StringUtils.isNotEmpty(remark)) {
//            crmWechatExternalContact.setName(getNoEmojiName(remark));
//        } else {
//            crmWechatExternalContact.setName(getNoEmojiName(externalContact.getName()));
//        }
//        crmWechatExternalContact.setExternalUserid(externalContact.getExternal_userid());
//        crmWechatExternalContact.setAvatar(externalContact.getAvatar());
//        crmWechatExternalContact.setGender(externalContact.getGender());
//        crmWechatExternalContact.setType(externalContact.getType());
//        return crmWechatExternalContact;
//    }
//
//    private String getNoEmojiName(String realName) {
//        boolean flag = UTF8MB4.containsMb4Char(realName);
//        if (flag) {
//            return UTF8MB4.replaceMb4Char(realName, "[表情包]");
//        } else {
//            return realName;
//        }
//    }
//
//}
